;(function () {
  var flowState = hlUrlUtil.GetQueryString('page') === 'XQ' ? false : true    // 查看状态为false  处理状态为true
  Array.prototype.removeRepeatBuildingAndFloor = function() {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };
  function toDou(num) {
    return num < 10 ? '0' + num : '' + num;
  }
  function time(oldTime) {
      // 此刻的时间
      if (!oldTime) return '00天00小时';
      var oDate = new Date();
      var iS = parseInt(((oDate.getTime()+8*60*60*1000) - oldTime) / 1000);
      var iD = parseInt(iS / 86400); // 天数
      iS %= 86400; // 转换成天数剩余的秒数 -> 小时
      var iH = parseInt(iS / 3600); // 小时
      iS %= 3600; // 转换成小时数剩余的秒数 -> 分钟
      var iM = parseInt(iS / 60); // 分钟
      iS %= 60; // 秒数
      return toDou(iD)+'天'+toDou(iH)+'小时'
  }

  new Vue({
    el:'#contractFLow',
    data:{
      auditState:'', // 合同状态
      contractId:hlUrlUtil.GetQueryString('businessId'),
      taskId:hlUrlUtil.GetQueryString('taskId'),
      bpmId:hlUrlUtil.GetQueryString('bpmId'),
      projectIds:hlUrlUtil.GetQueryString('projectIds'),
			permissions: JSON.parse(localStorage.getItem('permissions')),
      intentId:null,
      intentDeductibleAmount:0,
			payData: [],
      nav:[
        {
          name:'合同信息',
          iscur:true
        },
        {
          name:'流程信息',
          iscur:false
        },
        {
          name:'相关文件',
          iscur:false
        }
      ],
      contract:{cCode: '',commissionRules: [],expenses:[]},         // 合同信息
      contractFile:[],
      resourceMes:{
        st: [],
        ot: []
      },   // 资源信息
      building:[],  // 楼宇数据
      totalArea:0,
      unit:[], // 单元
      st: [], // 车位
      wp: [], // 工位
      rentPriceUnit:'D',
      isShowUnit:false,
      stTotalNum: 0, // 车位总数量
      wpTotalNum: 0, // 工位总数量
      freeDate: [], // 免租期
      rent:[],   // 租金
      pExpense:[], // 周期性费用
      oExpense:[], // 一次性费用
      tExpense:[], // 其他费用
      bpm:{},  // 工作流程信息
      flowNode:[], // 流程节点
      userid: JSON.parse(window.localStorage.getItem('userMes')).id,
      bpmList:[], // 工作流程列表
      currentNode:[], // 当前处理节点
      loadContractMesModule:true,
      loadFlowMesModule:false,
      loadRelevantFileModule:false,
      flowState:flowState,
      billFirstItemData:{
        'expenseList':[]
      },
      billOtherItemData:[],
      pExpenseName:[],  // 周期性费用名
      pExpensePrice:[],  // 每个账期周期性费用价格
      pExpensePrice2:[],  // 每项周期性费用总价格
      payPlanFlag:false,
      dayRentPriceAlert:'',
      monthRentPriceAlert:'',
      unitId:null,      // 单元id
      unitDetailsFlag:false,
      industryTypes:{list: []},
      ityName: null,
      //20190705
      TemTypeList: ['Word', 'PDF'],
      selectedTemTypeList: [],
      temList: [],
      selectedTemList: '',
      TemplateModulShow: false,
      isGDZJflag: false,
      isYJflag: false,
      approveFlag: null,
      tmpData: [],
      breakPriceFlag:'',

      contractBdate:'',
      contractEdate:'',
      effectiveRentDay:'',
      effectiveRentMonth:''
    },
    filters:{
      formatDate: function (time) {
        if (time === undefined) return '--'
        var date = new Date(time)
        return hlDateUtil.formatUTCDate(date, 'yyyy-MM-dd')
      },
      formatDetailDate:function (time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time)
      },
      formatUndefined:function (item) {
        if(item === undefined)return '--'
        return item
      },
      formatIndustry:function (item) {
        return hlCodeConvert.industryType(item)
      },
      formatNum:function (item) {
        if(item == '--')return'--'
        return hlNumberUtil.formatNum(item)
      },
      contractType:function(item){
        return hlCodeConvert.contractType(item)
      },
      contractAuditState:function(item){
        return hlCodeConvert.contractAuditState(item)
      },
      contractZlfType:function(item){
        return hlCodeConvert.contractZlfType(item)
      }
    },
    methods:{
       //导出合同模板
       exportTemplate() {
        if (!this.selectedTemTypeList.length) {
          hl.toast('请选择文件类型')
          return
        }
        if (!this.selectedTemList) {
          hl.toast('请选择模板')
          return
        }
        var that = this
        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/contract_export',
          data: {
            contract_id: that.contractId,
            template_id: that.selectedTemList,
            file_type: that.selectedTemTypeList.join(',')
          },
          success: function(data) {
            that.downloadFiles(data)
            that.TemplateModulShow = false
          }
        })
      },
      createIFrame(url) {
        setTimeout(() => {
          let frame = document.createElement('iframe');
          frame.style = 'display: none;';
          frame.class = 'multi-download';
          frame.src = url,
            document.body.appendChild(frame);
          setTimeout(function() {
            document.body.removeChild(frame);
          }, 1000);
        })
      },
      downloadFiles(fileUrls) {
        fileUrls.forEach(v => {
          this.createIFrame(v);
        })
      },
       //新增合同模板
       addNewTem() {
        hlUrlUtil.goTo('billTemplate', {
          ddtab: true
        }, true)
      },
       //合同预览/打印
       previewTemPrint() {
        this.TemplateModulShow = true
        var that = this
        hlhttp.get({
          url: 'contract/print_templates',
          success: function(data) {
            that.temList = data
          }
        })
      },
      //预览合同模板
      preview(id) {
        hlhttp.get({
          baseUrl: exclUrl,
          url: 'resource/contract_content_tempalte_preview',
          data: {
            template_id: id,
            contract_id:this.contractId,
            contract_info:'#'
          },
          success: function(data) {
            $.previewPDF(data.pdf_url)
          }
        })
      },
       //选择文档类型
       selectedTemType(item) {
        let index = this.selectedTemTypeList.indexOf(item)
        if (index > -1) {
          this.selectedTemTypeList.splice(index, 1)
        } else {
          this.selectedTemTypeList.push(item)
        }
      },
       //选择文档
       selectedTem(item) {
        this.selectedTemList = item.id
      },
      //催办
      cuiban: function () {
        var self = this;
        hlhttp.get({
          url: 'bpm/urge/time',
          data: {bpm_id: self.bpmId},
          success: function (res) {
            hllayer.promptSm({
              title:'催办',
              leftBtn:'确定',
              subTitle: '本操作将给处理人发送一条微信消息！',
              tips: '距离上次催办'+time(res.time),
              confirm:function (msg) {
                hlhttp.put({
                  url: 'bpm/urge',
                  data: {bpm_id: self.bpmId, task_id: self.taskId, memo: msg || '#'},
                  success: function () {
                    hl.toast('发送成功')
                    $('.hllayer-prompt,.hllayer-mask').remove()
                    self.getBpmDetailData()
                    self.getBpmListData()
                    self.getindustryTypes()
                  }
                })
              }
            })
          }
        })
      },
      //获取行业列表
      getindustryTypes: function () {
        var _this = this;
        hlhttp.get({
          url: 'configure/industry/dict',
          success: function (data) {
            _this.industryTypes.list = data;
            _this.getContractData()
          }
        })
      },
      // 计算每个周期账单的周期性费用
      everyPExpense: function () {
        var self = this;
        this.billOtherItemData.map(function (item) {
          var result = 0;
          item.expenseList.P.map(function (_item) {
            if(_item.expense != '--'){
              result += Number(_item.expense)
            }
          })
          self.pExpensePrice.push(result)
        })
      },
      // 计算每项周期性总费用
      pExpenseTotalPrice:function () {
        var self = this;
        var index = 0;
        for(var i = 0; i<self.pExpenseName.length; i++){
          var pExpense = 0;
          self.billFirstItemData.expenseList.P.map(function (item,index) {
            if(item.expense != '--' && index == i){
              pExpense += Number(item.expense)
            }
          })
          self.billOtherItemData.map(function (item,index) {
            item.expenseList.P.map(function (_item,_index) {
              if(_item.expense != '--' && _index == i)pExpense += Number(_item.expense)
              index++;
            })
          })
          self.pExpensePrice2.push(pExpense)
        }
      },
      // tab切换
      switchNav:function (item,index) {
        var self = this;
        console.log(self.payData);
        self.nav.map(function (_item,_i) {
          _i == index ? _item.iscur = true : _item.iscur = false;
        })
        if(index === 0){
          self.loadContractMesModule = true
          self.loadFlowMesModule = false
          self.loadRelevantFileModule = false
        }
        if(index === 1){
          self.loadContractMesModule = false
          self.loadFlowMesModule = true
          self.loadRelevantFileModule = false
        }
        if(index === 2){
          self.loadContractMesModule = false
          self.loadFlowMesModule = false
          self.loadRelevantFileModule = true
        }
      },
      // 获取合同数据
      getContractData:function () {
        var self = this;
        hlhttp.get({
          url:'contract',
          data:{id:self.contractId},
          success:function (data) {
          
             self.contractBdate = hlDateUtil.formatUTCDate(data.beginDate, 'yyyy-MM-dd')
             self.contractEdate = hlDateUtil.formatUTCDate(data.endDate, 'yyyy-MM-dd')

						self.tmpData = data.pageCustomizeComponentBizContentList
						
            if(data.customConfigProperty){
              data.customConfigProperty = JSON.parse(data.customConfigProperty)
            }
            data.expenses.some(item =>{
              if(item.expenseType == 'R'){
                self.isGDZJflag = true
              }
            })
            data.expenses.some(item =>{
              if(item.expenseType == 'D'){
                self.isYJflag = true
              }
            })
						if (!data.commissionRules) {
							data.commissionRules = []
						}
            self.contract = data
            self.auditState = data.auditState;
            self.intentId = data.relatedIntentId || null;
            self.intentDeductibleAmount = data.intentDeductibleAmount || 0 ;
            if(data.contractType === 'WR'){
              self.isShowUnit = false;
            }else{
              self.isShowUnit = true;
            }
            if(data.rentPriceUnit === 'D' && data.contractType === 'ER'){self.rentPriceUnit = 'DM'}
            if(data.rentPriceUnit === 'M' && data.contractType === 'ER'){self.rentPriceUnit = 'MM'}
            if(data.rentPriceUnit === 'D' && data.contractType === 'WR'){self.rentPriceUnit = 'DG'}
            if(data.rentPriceUnit === 'M' && data.contractType === 'WR'){self.rentPriceUnit = 'MG'}
            // 单元
            var buildingData = self.unitData(data.units)
            self.totalArea = data.rentAcreage
            self.building = buildingData.building
            // 车位
            self.unit = [];
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.units.map(function(item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
              if (item.unitType === 'BU') {
                self.unit.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
            // 租金数据
            self.rent = [];
            if(data.rentIncreseDate && data.rentIncreseDate.split(',').length > 1){
              for (var i = 1; i < data.rentIncreseDate.split(',').length; i++) {
                self.rent.push({
                  beginDate: data.rentIncreseDate.split(',')[i],
                  percent: data.rentIncresePercent.split(',')[i] ? data.rentIncresePercent.split(',')[i] : '',
                  price: data.rentIncresePrice ? data.rentIncresePrice.split(',')[i] : '',
                  dayPrice:data.rentIncreseDay ? data.rentIncreseDay.split(',')[i] : '',
                  monthPrice:data.rentIncreseMonth ?  data.rentIncreseMonth.split(',')[i] : ''
                })
              }
            }
            // 折扣月租金
            if (data.rentIncreseDiscountDay) {
              let arr1 = data.rentIncreseDiscountRate.split(',')
              let arr2 = data.rentIncreseDiscountDay.split(',')
              let arr3 = data.rentIncreseDiscountMonth.split(',')
              self.rent.map((item, index) => {
                item.discount = arr1[index + 1]
                item.discountD = arr2[index + 1]
                item.discountM = arr3[index + 1]
              })
            }
            // 合同免租期
            self.freeDate = [];
            if(data.freeDates){
              // for (var m = 0; m < data.freeDate.split(',').length; m++) {
              //   self.freeDate.push({
              //     beginDate: data.freeDate.split(',')[m].split('~')[0],
              //     endDate: data.freeDate.split(',')[m].split('~')[1]
              //   })
              // }
              self.freeDate = data.freeDates
            }
            // 费用数据
            self.pExpense = [];
            self.oExpense = [];
            self.tExpense = [];
            if(data.expenses){
              for (var j = 0; j < data.expenses.length; j++) {
                if (data.expenses[j].expenseType == 'P') {
                  self.pExpense.push(data.expenses[j])
                }
                if (data.expenses[j].expenseType == 'O') {
                  self.oExpense.push(data.expenses[j])
                }
                if (data.expenses[j].expenseType == 'T') {
                  self.tExpense.push(data.expenses[j])
                }
              }
            }
            // 合同文件数据
            if(data.attachmentNames){
              for (var k = 0; k < data.attachmentNames.length; k++) {
                var fileObj = {
                  name: data.attachmentNames[k],
                  url: data.attachmentUrls[k]
                }
                self.contractFile.push(fileObj)
              }
            }
            self.industryTypes.list.map(function (item) {
              if (self.contract.zlfIndustryType == item.dictCode) {
                self.ityName = item.dictName;
              }
            })
            self.dealWithbillData(data.compareRentAmtFlag)


          }
        })
      },
      // 获取破底价配置
      getBreakPrice(){
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'CIWU',
            'config_name': 'CW_BREAK_PRICE_REMINDER_TYPE_CONFIG'
          },
          success: res => {
            // CONTRASTPRICE 与预签约单价比较
            // CONTRASTRENT  与有效租金比较
            this.breakPriceFlag = res[0].dictValue == 'CONTRASTRENT'? 'CR':'CP'
          }
        })
      },
      // 判断价格是否符合底价策略
      isSatisfyMinPrice:function(num){
        var self = this;
        // 所选合同类型  WP 工位   UN 单元
        var type = self.contract.contractType === 'WR' ? 'WP' : 'UN'
        // 所选单元或者工位id  如果只选车位 则不掉用底价策略
        var getUnitIds = function(){
          var res = [];
          self.unit.map(function(_item){
            res.push(_item.unitId)
          })
          res = hlArrayUtil.arrUnique(res)
          return res.join()
        }
        var getWpIds = function(){
          var res = [];
          self.wp.map(function(item){
            item.positions.map(function(_item){
              res.push(_item.positionId)
            })
          })
          res = hlArrayUtil.arrUnique(res)
          return res.join()
        }
        var ids = null;
        if(type === 'WP'){ ids = getWpIds()}
        if(type === 'UN'){ ids = getUnitIds()}
        // 日租金、月租金计算
        var acreage = self.totalArea ? self.totalArea : this.wpTotalNum;
        var rentPriceDay = self.contract.rentPriceDay / acreage;
        var rentPriceMonth = self.contract.rentPriceMonth / acreage
        if(self.unit.length !== 0 || self.wp.length !== 0){
          hlhttp.put({
            url:'check_base_price_policy',
            data:{
              rent_price_day:Number(rentPriceDay).toFixed(2),
              rent_price_month:Number(rentPriceMonth).toFixed(2),
              type:type,
              ids:ids,
              policy_type:self.breakPriceFlag || '#',
              contract_amount:num || '#',
              contract_begin_date:self.contractBdate || '#',
              contract_end_date:self.contractEdate || '#',
            },
            success:function(data){
              if (data.result === 'N') {
                if (data.rentPriceType === 'D') {
                  if (type === 'WP') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/个/天,'):'')  + '低于工位底价' + data.memo + '元/个/天'
                    self.monthRentPriceAlert = ''
                  }
                  if (type === 'UN') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/m²/天,'):'')  + '低于单元底价' + data.memo + '元/m²/天'
                    self.monthRentPriceAlert = ''
                  }
                }
                if (data.rentPriceType === 'M') {
                  if (type === 'WP') {
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/个/月,'):'')  + '低于工位底价' + (Number(data.memo)).toFixed(2) + '元/个/月'
                    self.dayRentPriceAlert = ''
                  }
                  if (type === 'UN') {
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/m²/月,'):'')  + '低于单元底价' + (Number(data.memo)).toFixed(2) + '元/m²/月'
                    self.dayRentPriceAlert = ''
                  }
                }
                if (data.rentPriceType === 'A') {
                  if (type === 'WP') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/个/天,'):'')  + '低于工位底价' + data.memo.split(',')[0] + '元/个/天'
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/个/月,'):'')  + '低于工位底价' + Number(data.memo.split(',')[1] || '0').toFixed(2) + '元/个/月'
                  }
                  if (type === 'UN') {
                    self.dayRentPriceAlert = '日租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentDay + '元/m²/天,'):'')  + '低于单元底价' + data.memo.split(',')[0] + '元/m²/天'
                    self.monthRentPriceAlert = '月租金' + (self.breakPriceFlag == 'CR'?('有效租金' + data.effectiveRentMonth + '元/m²/月,'):'')  + '低于单元底价' + Number(data.memo.split(',')[1] || '0').toFixed(2) + '元/m²/月'
                  }
                }
              }
              if (data.result === 'Y') {
                self.dayRentPriceAlert = ''
                self.monthRentPriceAlert = ''
              }
              self.effectiveRentDay = data.effectiveRentDay
              self.effectiveRentMonth = data.effectiveRentMonth
            }
          })
        }
      },
      unitData:function(unitsData){
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function(_item){
          if(_item.positions.length === 0){ units.push(_item) }
        })
        if(units.length === 0){
          return {
            building:[],
            totalArea:0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i <units.length; i++) {
            unit.push({
              buildingName: units[i].buildingName,
              floorNum: units[i].floorNum,
              floorName: units[i].floorName,
              unit: [],
              unitId:[],
              originAcreage:[]
            })
        }
        var unitArr = unit.removeRepeatBuildingAndFloor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName+'('+ hlNumberUtil.formatNum(units[m].unitAcreage) +'m²)')
              unitArr[z].unitId.push(units[m].unitId)
              // 如果单元当前面积等于初始面积 则push undefined  反之push初始面积
              if(units[m].unitAcreage === units[m].originAcreage){
                unitArr[z].originAcreage.push('undefined')
              }else{
                unitArr[z].originAcreage.push(units[m].originAcreage)
              }
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j< unitArr.length; j++){
          building.push({
            buildingName: unitArr[j].buildingName,
            floor:[]
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building,'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum':unitArr[n].floorNum,
                'floorName':unitArr[n].floorName,
                'unit':unitArr[n].unit,
                'unitId':unitArr[n].unitId,
                'originAcreage':unitArr[n].originAcreage
              })
            }
          }
        }
        return {
          building:buildingArr,
          totalArea:totalArea
        }
      },
      // 展示单元原有面积
      showUnitOriginAcreage:function(i,val){
        if(val || val == 0){
          val = '原面积：' + hlNumberUtil.formatNum(val) + 'm²'
          hllayer.tips($($('.origin-acreage')[i]),val,true)
        }
      },
      hideUnitOriginAcreage:function(){
        return hllayer.closeall()
      },
      // 获取单元详情
      getUnitDetails:function(unitId){
        var self = this;
        self.unitId = unitId;
        self.unitDetailsFlag = true;
      },
      // 关闭单元详情弹出层
      closeUnitPop:function(state){
        this.unitId = null;
        this.unitDetailsFlag = false;
      },
      // 通过审核
      passAudit:function () {
        var self = this;
        hllayer.prompt({
          title:'审核通过',   // 标题  默认为空
          placeholder:'审核通过原因说明（非必填）',
          leftBtn:'提交',
          confirm:function (mes) {
            $('.hllayer-mask, .hllayer-view').remove()
            hlhttp.put({
              url:'bpm/_pass',
              data:{
                bpm_key: 'CT',
                task_id:self.taskId,
                bpm_id:self.bpmId,
                memo:mes || '#',
								state: self.contract.auditState
              },
              success:function (data) {
                hl.toast('审核通过')
                hllayer.close();
                self.flowState = false
                self.auditState = data.auditState;
                hlUrlUtil.goTo('todo', {stateName: 'CT',projectIds:self.projectIds, ddtab:true})
                //审核通过后更新流程信息
                self.getBpmDetailData()
                self.getBpmListData()
              }
            })
          }
        })
      },
      // 未通过审核
      notPassAudit:function () {
        var self = this;
        hllayer.prompt({
          title:'审核不通过',
          placeholder:'审核不通过原因说明（必填）',
          leftBtn:'提交',
          confirm:function (mes) {
            if(!mes){
              hl.toast('请填写审核不通过的原因')
              return
            }
            hlhttp.put({
              url:'bpm/_reject',
              data:{
                task_id:self.taskId,
                bpm_id:self.bpmId,
                memo:mes,
								state: self.contract.auditState
              },
              success:function (data) {
                hl.toast('审核不通过')
                hllayer.close();
                self.flowState = false
                self.auditState = data.auditState;
                hlUrlUtil.goTo('todo', {stateName: 'CT',projectIds:self.projectIds, ddtab:true})
                //审核通过后更新流程信息
                self.getBpmDetailData()
                self.getBpmListData()
              }
            })
          }
        })
      },
      // 获取流程详情数据
      getBpmDetailData:function () {
        var self = this;
        hlhttp.get({
          url:'bpm',
          data:{
            bpm_key:'CT',
            bpm_id:self.bpmId
          },
          success:function (data) {
            var newArr = data;
            var bpdefId = data.bpdefId || 0

            self.approveFlag = data.approveFlag
            self.$set(self.$data, 'bpm', newArr)
            self.getFlowNodeData(bpdefId)
          }
        })
      },
      // 获取流程节点数据
      getFlowNodeData:function (id) {
        var self = this;
        // 当所传id为0时展示最初始的业务节点图   ====>  开始 ----- 合同审核  ----- 结束
        if(id === 0){
          var nodeData = [{
            name:'合同审核'
          }]
          self.flowNode = nodeData;
        }
        if(id !== 0){
          hlhttp.get({
            url:'bpdef_phases',
            data:{'bpdef_id':id},
            success:function(data){
              self.flowNode = data
            }
          })
        }
      },
      // 获取工作流程任务列表数据
      getBpmListData:function () {
        var self = this;
        hlhttp.get({
          url:'bpm/tasks',
          data:{bpm_id:self.bpmId},
          success:function (data) {
            var newArr = [];
            for(var i = 0; i<data.length; i++){
              if(data[i]['endTime'])newArr.push(data[i]);
            }
            self.$set(self.$data, 'bpmList', newArr)
          }
        })
      },
      // 撤回
      withdrawCH: function () {
        var self = this;
        hllayer.confirm('撤回后，流程将立即终止', function() {
          hlhttp.delete({
            url: 'bpm/_withdraw?bpm_id=' + self.bpmId,
            success: function () {
              hl.toast('撤回成功')
              hlUrlUtil.goTo('myFlowList', {projectIds: self.projectIds, ddtab:true})
            }
          })
        })
      },
      // 导出账单
      exportBill:function () {
        var self = this;
        $.ajax({
          url: exclUrl+'resource/bill_excel',
          type: 'get',
          headers: {token: Cookies.get("token")},
          data: {contract_id: self.contractId},
          success: function (res) {
            var a = document.createElement('a');
            a.href = res.excel_url;
            $('body').append($(a))
            a.click();
            setTimeout(function() {
              $(a).remove()
            }, 100);
          }
        })
      },
      // 上传合同
      uploadFile:function(){
        $('.upload-file').trigger('click')
      },
      // 付款计划数据处理
      dealWithbillData:function (compareRentAmtFlag) {
        var self = this;
        hlhttp.get({
          url: 'contracts/bill_plans',
          data: {contract_id:self.contractId},
          success: function(data) {
            self.payData = data;
            setTimeout(()=>{
              console.log(self.$refs.payData)
              let arr = self.$refs.payData.subtotalArr.R || []
              let gdzj = ''
              arr.map(item =>{
                if(item.name == "固定租金"){
                  gdzj = item.expense
                }
              })
              self.isSatisfyMinPrice(gdzj)
            },500)
          }
        })
      },
      calculateTimeDifference:function(item1,item2){
        return hlDateUtil.timeDifference(item1,item2)
      },
      previewImage:function(url){
        var imageExt = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'];
        var pdfExt = ['pdf', 'PDF'];
        var officeExt = ['docx','doc','xlsx','xls','xlt']
        var imageFlag = false;
        var pdfFlag = false;
        var officeFlag = false;
        imageExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) imageFlag = true;
        })
        if (imageFlag) {
          $.imageShow([url])
          return
        }
        pdfExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) pdfFlag = true;
        })
        if (pdfFlag) {
          $.previewPDF(url)
          return
        }
        officeExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) officeFlag = true
        })
        if (officeFlag) {
          $.previewOffice(url)
          return
        }
        hl.toast('暂不支持该格式')
      }
    },
    computed:{
      // 首期账单总价格
      firstItemPrice:function () {
        var rExpense = Number(this.billFirstItemData.expenseList.R[0].expense);
        var pExpense = 0,oExpense = 0,iExpense = 0;
        this.billFirstItemData.expenseList.P.map(function (_item,_index) {
          if(_item.expense != '--')pExpense += Number(_item.expense)
        })
        this.billFirstItemData.expenseList.O.map(function (_item,_index) {
          oExpense += Number(_item.expense)
        })
        this.billFirstItemData.expenseList.I.map(function (_item,_index) {
          iExpense -= Number(_item.expense)
        })
        return (rExpense + pExpense + oExpense + iExpense).toFixed(2);
      },
      // 固定租金总价钱
      rentTotalPrice:function () {
        var firstItem = Number(this.billFirstItemData.expenseList.R[0].expense);
        var otherItem = 0;
        this.billOtherItemData.map(function (item) {
          item.expenseList.R.map(function (_item,_index) {
            if(_item.expense != '--')otherItem += Number(_item.expense)
          })
        })
        return firstItem + otherItem;
      },
      // 一次性费用总价钱
      oExpenseTotalPrice:function () {
        var oExpense = 0;
        this.billFirstItemData.expenseList.O.map(function (_item,_index) {
          oExpense += Number(_item.expense)
        })
        return oExpense;
      },
      // 总价钱
      totalPrice:function () {
        var pExpenseTotalPrice = 0;
        if(this.pExpensePrice2.length !== 0){
          this.pExpensePrice2.map(function (item) {
            pExpenseTotalPrice += item
          })
        }
        return (this.rentTotalPrice + this.oExpenseTotalPrice + pExpenseTotalPrice - this.intentDeductibleAmount).toFixed(2)
      },
      adjust:function () {
        var pExpenseWidthTotal = this.pExpense.length * 120;
        var otherWidth = 580;
        var intentWidth = this.intentId ? 120 : 0;
        var hjWidth = 110;
        if(otherWidth + pExpenseWidthTotal + hjWidth + intentWidth  > 950)return
        if(otherWidth + pExpenseWidthTotal + hjWidth + intentWidth < 950){
          hjWidth = 950 - otherWidth - pExpenseWidthTotal - intentWidth
        }
        return hjWidth + 'px'
      },
      totalPriceWidth:function () {
        var totalNum = 2;
        var intentLength = this.intentId ? 1 : 0 ;
        totalNum = this.pExpense.length + intentLength + totalNum;
        if(totalNum <= 7){
          return 830/totalNum + 'px'
        }
      },
      // 付款计划内层横向滑动宽度
      coreWidth:function () {
        var pExpenseWidthTotal = this.pExpense.length * 120;
        var otherWidth = 580;
        var hjWidth = 110;
        var coreWidth = 955;
        // 是否存在意向金抵扣
        var intentWidth = this.intentId ? 120 : 0;
        if(otherWidth + pExpenseWidthTotal + hjWidth + intentWidth < 950)return coreWidth + 'px'
        if(otherWidth + pExpenseWidthTotal + hjWidth + intentWidth > 950){
          return otherWidth + pExpenseWidthTotal + hjWidth + intentWidth + 'px'
        }
      },
      // 付款总额内层横向滑动宽度
      coreTotalWidth:function () {
        var totalNum = 1;
        if(this.oExpense.length !== 0){
          totalNum++;
        }
        totalNum = this.pExpense.length + totalNum;
        if(totalNum > 7)return totalNum * 120 + 120 + 'px'
      },
      yaTotal(){
        let num = 0
        this.contract.expenses.map(item =>{
          if(item.expenseType == 'D'){
            num = num + Number(item.amount)
          }
        })
        return num.toFixed(2)
      }
    },
    mounted:function () {
      this.getBpmDetailData()
      this.getBpmListData()
      this.getindustryTypes()
      this.getBreakPrice()

			var self = this;
			fileUpload('.upload-file', uploadUrl, function(src) {
			  if (src.json == undefined) return false;
			  hlhttp.post({
			    url: 'contract_attachment',
			    data: {
			      contract_id: self.contractId,
			      attachment_names: src.json.name,
			      attachment_url: src.json.url
			    },
			    success: function() {
			      hl.toast('上传成功')
			      self.contractFile.push({
			        name: src.json.name,
			        url: src.json.url
			      })
			    }
			  })
			})
    }
  })
}())
